package com.chagee.store.operation.server.mq;

import com.alibaba.fastjson.JSON;
import com.chagee.store.operation.common.constant.CommonConstant;
import com.chagee.store.operation.common.exception.BizErrorCode;
import com.chagee.store.operation.common.exception.BizException;
import com.chagee.store.operation.server.model.param.WorkOrderExpiredTaskMqBody;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @ClassName WorkOrderTaskMqProduct  //类名称
 * @Description: 类描述：将每个工单放入延迟队列内等待10h后消费（将不是待验收，已完成，已过期的工单--->已过期）
 * @Author: Jacky-zhan	//作者
 * @CreateDate: 2024/3/21 13:51	//创建时间
 * @UpdateUser: Jacky-zhan
 * @UpdateDate: 2024/3/21 13:51	//更新时间
 * @UpdateRemark: 更新的信息
 * @Version: 1.0    //版本号
 */
@Slf4j
@Service
public class WorkOrderExpiredTaskMqProduct {

	@Resource(name = "rocketMQTemplate")
	private RocketMQTemplate rocketMqTemplate;

	@Value("${threePartyClosing.delaySeconds:39600}")
	private int delaySeconds;

	public Boolean producerMessage(WorkOrderExpiredTaskMqBody body) {
		log.info("工单创建,mq生产者--入参[body = {}]", body);
		try {
			org.apache.rocketmq.common.message.Message message = new org.apache.rocketmq.common.message.Message(CommonConstant.CLOSE_CLEAN_ORDER_DELAY_TOPIC, JSON.toJSONString(body).getBytes());
			DefaultMQProducer producer = rocketMqTemplate.getProducer();
//			SendResult sendResult = rocketMqTemplate.syncSendDelayTimeSeconds(CommonConstant.CLOSE_CLEAN_ORDER_DELAY_TOPIC, MessageBuilder.withPayload(body).build(), delaySeconds);
			message.setDeliverTimeMs(System.currentTimeMillis() + (delaySeconds * 1000L));
			SendResult sendResult = producer.send(message);
			log.info("工单创建,mq生产者--结果 result:{}", JSON.toJSONString(sendResult));
			if (sendResult.getSendStatus().equals(SendStatus.SEND_OK)) {
				return true;
			}
		} catch (Exception e) {
			log.error("工单创建,mq生产者--异常 topic:{}:{}", CommonConstant.CLOSE_CLEAN_ORDER_DELAY_TOPIC, JSON.toJSONString(body), e);
			throw new BizException(BizErrorCode.MQ_SEND_FAIL);
		}
		return false;
	}

}
